package org.idea.spring.framework.event;

import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationEvent;
import org.springframework.context.ApplicationListener;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.event.*;
import org.springframework.context.support.AbstractApplicationContext;
import org.springframework.scheduling.concurrent.CustomizableThreadFactory;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * 自定义的同步异步转换事件案例
 *
 * @Author linhao
 * @Date created in 11:33 上午 2021/5/30
 */
public class MyAsyncEventDemo {

    private static ExecutorService taskExecutor;

    public static void main(String[] args) throws InterruptedException {
        AnnotationConfigApplicationContext annotationConfigApplicationContext = new AnnotationConfigApplicationContext();
        annotationConfigApplicationContext.register(MyAsyncEventDemo.class);
        annotationConfigApplicationContext.register(MySpringEventListener.class);
        annotationConfigApplicationContext.refresh();

        ApplicationEventMulticaster applicationEventMulticaster = annotationConfigApplicationContext.getBean(AbstractApplicationContext.APPLICATION_EVENT_MULTICASTER_BEAN_NAME, ApplicationEventMulticaster.class);
        if (applicationEventMulticaster instanceof SimpleApplicationEventMulticaster) {
            SimpleApplicationEventMulticaster simpleApplicationEventMulticaster = (SimpleApplicationEventMulticaster) applicationEventMulticaster;
            taskExecutor = Executors.newFixedThreadPool(5,new CustomizableThreadFactory("pool-idea-01"));
            simpleApplicationEventMulticaster.setTaskExecutor(taskExecutor);
            simpleApplicationEventMulticaster.addApplicationListener(new ApplicationListener<ContextClosedEvent>() {
                @Override
                public void onApplicationEvent(ContextClosedEvent event) {
                    if (!taskExecutor.isShutdown()) {
                        taskExecutor.shutdown();
                    }
                }
            });
        }
        Thread.sleep(3000);
        System.out.println("进入关闭阶段");
        annotationConfigApplicationContext.close();
    }

    static class MySpringEventListener implements ApplicationListener {

        @Override
        public void onApplicationEvent(ApplicationEvent event) {
            System.out.printf("thread is %s,accept event is %s \n", Thread.currentThread().getName(), event);
        }
    }


}
